using AppToolKit.Core.AttributeDiscovery;
using System;
using System.Collections.Generic;
using System.Reflection;
namespace AppToolKit.Core.Context
{
	public class UniqueImplAttributeProcessor : FeatureProcessorBase, IScopeImplManager
	{
		private Dictionary<string, Dictionary<Type, Type>> map_ = new Dictionary<string, Dictionary<Type, Type>>();
		public Type GetUnqiureTypeByScope(string scope, Type intefaceType)
		{
			Type result;
			if (this.map_.ContainsKey(scope) && this.map_[scope].ContainsKey(intefaceType))
			{
				result = this.map_[scope][intefaceType];
			}
			else
			{
				result = null;
			}
			return result;
		}
		public override bool IsSupport(Assembly assembly)
		{
			return base.IsSupport(assembly);
		}
		public override void Process(Type type, FeatureProcessContext ctx)
		{
			if (type.IsDefined(typeof(UniqueImplAttribute), false))
			{
				UniqueImplAttribute uniqueImplAttribute = (UniqueImplAttribute)type.GetCustomAttributes(typeof(UniqueImplAttribute), false)[0];
				if (TypeHelper.IsInheritInterface(type, uniqueImplAttribute.InterfaceType))
				{
					string key;
					if (uniqueImplAttribute.Scope == ContextScope.Assembly)
					{
						key = type.Assembly.FullName;
					}
					else
					{
						key = "APPLICATION_SCOPE";
					}
					if (!this.map_.ContainsKey(key))
					{
						this.map_[key] = new Dictionary<Type, Type>();
					}
					if (this.map_[key].ContainsKey(uniqueImplAttribute.InterfaceType))
					{
						throw new FeatureDetectExecption(string.Format("{0} Not Unqiure Implatement {1}", type, uniqueImplAttribute.InterfaceType));
					}
					this.map_[type.Assembly.FullName][uniqueImplAttribute.InterfaceType] = type;
				}
			}
		}
	}
}
